import './libs/md5'

(function(){

    function Native() { };

    function NException(message, name, error) {
        this.message = message;
        this.name = name;
        if (error) {
            this.error = error;
        }
    }

    Native.prototype = window.NBase || {};
    Native.prototype.base = function (handlerName, params) {
        return this.java(handlerName, params, 'NBase');
    }
    Native.prototype.java = function (handler, params, className, errorHandler, successHandler) {
        var error = null, reuslt;
        if (!window[className || 'Native']) {
            error = new NException("javascript接口类未注册", className || 'Native');
        } else if (!window[className || 'Native'][handler]) {
            error = new NException("接口未注册该方法", handler);
        }
        try {
            if (params != null && params != undefined) {
                if (params instanceof Object && !(params instanceof Array)) {
                    params = [JSON.stringify(params)];
                } else if (typeof params == 'string') {
                    params = [params];
                } else if (params instanceof Array) {
                    params = params;
                } else if (typeof params == "number") {
                    params = [String(params)];
                } else {
                    throw new NException("参数错误，必须要求为字符串String，或者是Array及其子类", params);
                }
            } else {
                params = [];
            }
            
            for (var i = 0; i < params.length; i++) {
                if (typeof params[i] == 'string') {
                    params[i] = params[i].replace(/\"/gi, '\\\"');
                }
            }
            params = params.length ? params.join('","') : null;
            reuslt = eval((className || 'Native') + '.' + handler + '(' + (params ? ('"' + params + '"') : '') + ')');
            console.log((className || 'Native') + ':' + handler + ':' + params);

            try {
                reuslt = reuslt ? JSON.parse(reuslt) : {};
                return reuslt;
            } catch (e) {
                errorHandler && errorHandler(reuslt);
                return reuslt || true;
            }
        } catch (e) {
            try {
                throw new NException("执行代码出错，请检查\"参数\"是否正确或者\"native代码\"", handler, error);
            } catch (e) {
                console.log(e);
                errorHandler && errorHandler();
                return false;
            }
        }
    };
    Native.prototype.api = Native.prototype.java;

    var property = {
        getMetaValue: function(attribute) {
            var node = document.querySelector('meta[' + attribute + ']');
            if(!node){
                return null;
            }
            return attrValue;
        },
        getWebVersion: function() {
            var version = this.getMetaValue('version');
            return version;
        },
        getWebBuild: function() {
            var version = this.getMetaValue('build');
            return version;
        },
        getNativeVersion: function() {
            return window.ZC.version;
        },
        getDevice: function () {
            return '0'
        },
        getDeviceId: function () {
            var canvas = document.createElement('canvas');
            var ctx = canvas.getContext('2d');
            var txt = 'http://www.zcareze.com/';
            ctx.textBaseline = "top";
            ctx.font = "14px 'Arial'";
            ctx.textBaseline = "tencent";
            ctx.fillStyle = "#f60";
            ctx.fillRect(125, 1, 62, 20);
            ctx.fillStyle = "#069";
            ctx.fillText(txt, 2, 15);
            ctx.fillStyle = "rgba(102, 204, 0, 0.7)";
            ctx.fillText(txt, 4, 17);
            var b64 = canvas.toDataURL().replace("data:image/png;base64,", "");
            var bin = atob(b64);
            var crc = Math.MD5(bin).toString();
            return crc;
        },
        getSystem: function () {
            return 'android';
        },
        closeApp: function () {
            window.close();
        }
    }

    var App = function () {
        var JavascriptAPI = {};
        var FUNCTION = 'function';
        var go = function (apply) {
            setTimeout(apply)
        }
        this.property = property;
        this.ClientService = {
            appinfo: {
                cloudId: "",
                terminal: property.getMetaValue('terminal'),
                deviceId: property.getDeviceId(),
                system: property.getSystem()
            }
        };

        this.Native = new Native();

        this.ReadyUpdateRelease = function () {
            var installhint = NApp.status.status == 2 ? '准备更新' : "同步数据";
            console.log(installhint)
        }

        this.UpdateReleaseProgress = function (result) {
            var text = "";
            if (result.type) {
                text = NApp.status.status == 2 ? '准备更新' : "同步数据";
            }
            result.data = result.data || result.params;
            if (result.data && result.data.contentLength) {
                newReleaseSize = result.data.contentLength;
            }
            if (result.data.progress > newReleaseSize) {
                newReleaseSize = result.data.progress
            }
            text = Math.floor(result.data.progress / newReleaseSize * 100) + '%';
            if (NApp.status.status == 2) {
                console.log('正在获取新版本程序' + text)
            } else {
                console.log('同步数据(' + text+ ')')
            }
        }

        this.UnZipRelease = function () {
        }

        this.UnZipReleaseProgress = function (result) {
            var text = "";
            if (result.type) {
                text = NApp.status.status == 2 ? '准备安装' : "处理数据";
            }
            result.data = result.data || result.params;
            if (result.data && result.data.contentLength) {
                newReleaseSize = result.data.contentLength;
            }
            if (result.data.progress > newReleaseSize) {
                newReleaseSize = result.data.progress
            }
            text = Math.floor(result.data.progress / newReleaseSize * 100) + '%';
            if (NApp.status.status == 2) {
                console.log('正在安装新版本程序' + text)
            } else {
                console.log('处理数据(' + text+')')
            }
        }
        this.SetupComplete = function (version) {
            window.NBase.restart();
        }
        this.AddJsAPI = function (name, handler) {
            JavascriptAPI[name] = handler;
        }

        this.RemoveJsAPI = function (name) {
            delete JavascriptAPI[name];
        }

        this.ExecuteJsAPI = function (name, params) {
            var self = this;
            go(function () {
                if ((JavascriptAPI[name] && typeof JavascriptAPI[name] == FUNCTION)) {
                    JavascriptAPI[name](params);
                } else if (self[name]) {
                    self[name](params);
                }
            })
        }
    };

    var NApp = new App();
    window.NApp = NApp;
})()